<?php

namespace app\common\model;

use think\Db;
use think\Model;


class AgentAdmin extends Model
{

    

    

    // 表名
    protected $name = 'agent_admin';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
		'status_text'
    ];
    
	const STATUS_NORMAL = 1;
	const STATUS_WAIT = 2;
	const STATUS_DEL = 0;
    
	public static $statusList = [
		self::STATUS_NORMAL => '正常',
		self::STATUS_WAIT => '审核中',
		self::STATUS_DEL => '已删除'
	];

	public function getStatusTextAttr($value, $data) {
		$value = $value ? : $data['status'];
		$list = self::$statusList;
		return $list[$value] ?? '';
	}

	public function user() {
		return $this->belongsTo('user', 'user_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	public function agent() {
		return $this->belongsTo('agentShop', 'agent_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	/**
	 * 获取代理管理员
	 * @param $agentId
	 * @return false|\PDOStatement|string|\think\Collection
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function getAdminListByAgentId($agentId) {
		
		$rows = Db::name('agentAdmin')->alias('a')
			->join('user u', 'a.user_id = u.id', 'left')
			->where('a.agent_id', $agentId)
			->where('a.status', 'neq', self::STATUS_DEL)
			->order('a.create_time desc')
			->field('a.id, a.status, u.nickname')
			->select();
		
		if($rows) {
			$statusList = self::$statusList;
			foreach ($rows as &$row) {
				$row['status_text'] = $statusList[$row['status']];
			}
		}
		return $rows;
		
	}
	
	
	/**
	 * 添加数据
	 * @param $userId
	 * @param $agentId
	 * @return boolean
	 */
	public function add($userId, $agentId) {
		$res = $this->isUpdate(false)
			->save([
				'user_id' => $userId,
				'agent_id' => $agentId,
				'status' => self::STATUS_WAIT
			]);
		return $res;
	}
	
	/**
	 * 更改状态
	 * @param $id
	 * @param $agentId
	 * @param $status
	 * @return boolean
	 */
	public function changetStatus($id, $agentId,  $status) {
		$res = $this->save(['status' => $status, 'agent_id' => $agentId], ['id' => $id]);
		return $res;
	}
	
	public static function getAdminLevel($userId) {
		$row = Db::name('agentAdmin')->alias('aa')
			->join('agentShop a', 'aa.agent_id = a.id', 'left')
			->where(['aa.user_id' => $userId, 'aa.status' => self::STATUS_NORMAL])
			->field('a.id, a.role, a.user_id')
			->find();
		return $row ? $row : false;
	}
}
